package com.hr.pong.service;

import com.google.common.util.concurrent.RateLimiter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class RateLimitedService {

  private static final Logger log = LoggerFactory.getLogger(RateLimitedService.class);
  private final RateLimiter rateLimiterTwo;
  private final RateLimiter rateLimiterOne;
  private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  public RateLimitedService() {
    rateLimiterTwo = RateLimiter.create(2.0);
    rateLimiterOne = RateLimiter.create(1.0);
  }

  public String handleRequestTwo() {
    boolean acquired = rateLimiterTwo.tryAcquire();
    if (acquired) {
      return processRequest();
    } else {
      return handleRateLimit();
    }
  }

  public String handleRequestOne() {
    boolean acquired = rateLimiterOne.tryAcquire();
    LocalDateTime now = LocalDateTime.now();
    if (acquired) {
      log.info("Request processed successfully,time:{},ThreadID:{}", now.format(formatter), Thread.currentThread().getId());
      return "World";
    } else {
      log.info("Two requests come in within the same second, but only one request is allowed per second,time:{}", now.format(formatter));
      return String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value());
    }
  }


  private String processRequest() {
    return handleRequestOne();
  }

  private String handleRateLimit() {
    LocalDateTime now = LocalDateTime.now();
    log.info("Request is rate-limited,time:{},threadID:{}", now.format(formatter), Thread.currentThread().getId());
    return String.valueOf(HttpStatus.TOO_MANY_REQUESTS.value());
  }
}
